<template>
  <div>
    <el-alert
      v-show="showText"
      :title="`支持扩展名：${
        accept ? accept : '.doc .docx .pdf .txt .xlsx .ppt .jpg .png .jpeg .glb'
      }，文件大小不能超过50M`"
      type="warning"
      show-icon
      :closable="false"
      style="margin: 0px 0 10px; background-color: transparent; padding: 0"
    />
    <ul>
      <el-upload
        :ref="`upload${keys}`"
        :name="`upload${keys}`"
        action="#"
        list-type="picture-card"
        :auto-upload="false"
        :on-change="handlePictureCardChange"
        v-model:file-list="fileList"
        :disabled="isRead"
        :accept="accept"
        :multiple="multiple"
        :class="isRead || fileList.length >= 1 ? 'hideInput' : 'showInput'"
      >
        <el-icon><Plus /></el-icon>
        <template #file="{ file }">
          <div>
            <img
              class="el-upload-list__item-thumbnail"
              :src="isImage(file) ? file.url : pic2"
              :style="
                !isImage(file) ? 'width:80%; margin: auto;display: flex;' : ''
              "
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                v-show="isImageOrPDF(file)"
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <el-icon><zoom-in /></el-icon>
              </span>
              <span
                v-show="!isImageOrPDF(file)"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <el-icon><Download /></el-icon>
              </span>
              <span
                v-show="!isRead"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
          <!-- <el-tooltip
            v-if="file.originalfilename?.length > 15"
            :content="file.originalfilename || ''"
            effect="customized"
          >
            <div class="alias oneLine file_name">
              {{ file.originalfilename || "" }}
            </div>
          </el-tooltip>
          <div v-else class="alias oneLine file_name">
            {{ file.originalfilename || "" }}
          </div> -->
        </template>
      </el-upload>
    </ul>
    <el-dialog :close-on-click-modal="false" v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import pic2 from "@/assets/images/document2.png";
import { ref } from "vue";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import request from "@/utils/request";
import type { UploadFile } from "element-plus";

defineOptions({
  name: "GENERALDOCUMENTUPLOAD",
  inheritAttrs: false,
});

const props = defineProps({
  // 回显的文件数据
  files: {
    type: Array,
    default: () => [],
  },
  // 一个页面中 多个文件上传组件
  keys: {
    type: Number,
    default: 1,
  },
  // 是否可编辑参数
  isRead: {
    type: Boolean,
    default: false,
  },
  // 多选
  multiple: {
    type: Boolean,
    default: true,
  },
  // 接受类型 .png,.jpeg,.jpg
  accept: {
    type: String,
    default: "",
  },
  // 是否显示提示文字
  showText: {
    type: Boolean,
    default: true,
  },
});

const { isRead, keys, files, multiple, accept, showText } = toRefs(props);

const emit = defineEmits(["update-files"]);

const uploadApi = import.meta.env.VITE_APP_BASE_API;

// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

// 上传统一文件夹名称
const folderName = ref("eam/equ/generaldocument");

// 预览url前缀
// const upDownLoadUrl = `${uploadApi}/system/fileCenter/download/`;

const realList = ref();

const fileList = ref<any[]>([]);

// 图片链接处理
function handleImageUrl(list: any) {
  const newList = JSON.parse(JSON.stringify(list));
  newList.forEach((item: any) => {
    item.realUrl = item.url;
    item.url = `${upPreviewUrl}${item.realUrl}`;
  });
  return newList;
}

watch(
  () => fileList,
  (newVal) => {
    const lists = JSON.parse(JSON.stringify(newVal.value));
    lists.forEach((item: any) => {
      item.url = item.realUrl;
      delete item.realUrl;
    });
    realList.value = lists;
  },
  {
    deep: true,
  }
);

watch(
  () => files,
  (newFile) => {
    fileList.value = handleImageUrl(newFile.value);
  },
  {
    immediate: true,
  }
);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

function isImage(file: UploadFile) {
  const imageTypes = [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/bmp",
    "image/webp",
    "jpeg",
    "jpg",
    "png",
    "gif",
    "bmp",
    "webp",
  ];
  return imageTypes.includes(file?.fileType);
}

function isImageOrPDF(file: UploadFile) {
  const imageTypes = [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/bmp",
    "image/webp",
    "jpeg",
    "jpg",
    "png",
    "gif",
    "bmp",
    "webp",
    "pdf",
  ];
  return imageTypes.includes(file?.fileType);
}

const handleRemove = async (file: UploadFile) => {
  let fileIndex = 0;
  for (let i = 0; i < fileList.value.length; i++) {
    if (fileList.value[i] === file) {
      fileIndex = i;
      break;
    }
  }
  fileList.value.splice(fileIndex, 1);
  setTimeout(() => {
    emit("update-files", realList.value);
  }, 100);
};

const handlePictureCardPreview = (file: UploadFile) => {
  if (isImageOrPDF(file)) {
    let url = file.url;
    url = url?.replace("fileCenter/download/", "fileCenter/preview/");
    window.open(url);
  } else {
    dialogImageUrl.value = file.url!;
    dialogVisible.value = true;
  }
};

const handleDownload = (file: UploadFile) => {
  let downloadElement = document.createElement("a");
  // 创建下载的链接
  downloadElement.href = file.url;
  // 下载后文件名
  downloadElement.download = file.name;
  document.body.appendChild(downloadElement);
  // 点击下载
  downloadElement.click();
  // 下载完成移除元素
  document.body.removeChild(downloadElement);
};

function uploadFileApi(file: File): any {
  const formData = new FormData();
  formData.append("file", file);
  return request({
    url: `/system/fileCenter/uploadFile/${folderName.value}`,
    method: "POST",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

const addFileList: any = ref([]);
// 上传
const handlePictureCardChange = async (uploadFile: any) => {
  const elderList = JSON.parse(JSON.stringify(fileList.value));
  try {
    const { data }: any = await uploadFileApi(uploadFile.raw).catch((e) => {
      fileList.value.pop();
      return;
    });
    // addFileList.value = [];
    addFileList.value.push({
      name: data.originalFilename,
      originalfilename: data.originalFilename,
      filename: data.fileName,
      fileType: data.fileType,
      path: data.path,
      realUrl: data.url,
      url: isImageOrPDF(data)
        ? `${import.meta.env.VITE_APP_BASE_API}/system/fileCenter/preview/${
            data.url
          }`
        : `${import.meta.env.VITE_APP_BASE_API}/system/fileCenter/download/${
            data.url
          }`,
    });
    fileList.value = [...elderList, ...addFileList.value];
    setTimeout(() => {
      emit("update-files", realList.value);
    }, 100);

    // 异步清除队列中的添加列表
    setTimeout(() => {
      addFileList.value = [];
    }, 400);
    return;
  } catch {
    return;
  }
};

onMounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    overflow: visible;
    margin: 0 20px 40px 0;
    justify-content: center;
  }
  .el-upload-list__item-thumbnail {
    object-fit: cover;
  }
}
:deep(.el-dialog .el-dialog__header) {
  border-bottom: none;
}
.file_name {
  position: absolute;
  bottom: -28px;
  z-index: 99;
  width: 100%;
}
.hideInput {
  :deep(.el-upload--picture-card) {
    display: none;
  }
}
</style>
